﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
using System.Text;

namespace mds.PullInAPIService
{
   public class JdAPIAdpater
    {
        /// <summary>
        /// AppKey
        /// </summary>
        private static string AppKey ="";
        /// <summary>
        /// Secret
        /// </summary>
        private static string Secret ="";
        /// <summary>
        /// Api协议版本
        /// </summary>
        private static string Version ="";
        /// <summary>
        /// 当前时间戳
        /// </summary>
        private string CurrentTimeStamp
        {
            get
            {
                return ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
            }
        }
        /// <summary>
        /// 发起请求并获得接口返回的结果（json字符串）
        /// </summary>
        /// <param name="method"></param>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        protected string WebRequest(string method, string url, string postData)
        {
            method = method.ToUpper();
            HttpWebRequest webRequest = null;
            StreamWriter requestWriter = null;
            string responseData = "";

            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((a, b, c, d) => { return true; });
            webRequest = System.Net.WebRequest.Create(method == "GET" ? string.Format("{0}?{1}", url, postData) : url) as HttpWebRequest;
            webRequest.Method = method.ToString();
            webRequest.ProtocolVersion = HttpVersion.Version10;
            webRequest.ServicePoint.Expect100Continue = false;

            if (method == "POST")
            {
                webRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                requestWriter = new StreamWriter(webRequest.GetRequestStream());
                requestWriter.Write(postData);
                requestWriter.Close();
                requestWriter = null;
            }
            responseData = WebResponseGet(webRequest);
            webRequest = null;
            return responseData;
        }

        private string WebResponseGet(HttpWebRequest webRequest)
        {
            StreamReader responseReader = null;
            string responseData = string.Empty;
            responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
            responseData = responseReader.ReadToEnd();
            webRequest.GetResponse().GetResponseStream().Close();
            responseReader.Close();
            responseReader = null;

            return responseData;
        }

        /// <summary>
        /// 根据接口参数生成签名
        /// </summary>
        /// <param name="parameters">接口参数列表</param>
        /// <param name="secret">secret</param>
        /// <returns></returns>
        private static string CreateSign(IDictionary<string, string> parameters)
        {
            if (parameters.ContainsKey("sign"))
                parameters.Remove("sign");
            IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
            IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
            StringBuilder query = new StringBuilder(Secret);
            while (dem.MoveNext())
            {
                string key = dem.Current.Key.ToString();
                string value = dem.Current.Value;
                if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                {
                    query.Append(key).Append(value);
                }
            }
            query.Append(Secret);
            MD5 md5 = MD5.Create();
            byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));
            StringBuilder result = new StringBuilder();

            for (int i = 0; i < bytes.Length; i++)
            {
                string hex = bytes[i].ToString("X");
                if (hex.Length == 1)
                {
                    result.Append(0);
                }
                result.Append(hex);
            }

            return result.ToString();
        }
    }
}
